package com.lay.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lay.entity.Power;
import com.lay.service.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.Filter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

// AuthorizationFilter抽象类实现了javax.servlet.Filter接口，它是个过滤器。
@WebFilter(filterName = "CustomRolesAuthorizationFilter",urlPatterns = "/**")
@Component
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {
    @Autowired
    private PowerService powerService;


    @Override
    protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
        //存放的是当前登录用户的 角色
        Subject subject = getSubject(req, resp);
        String principal = String.valueOf(subject.getPrincipals());
        //rolesArray存放的是配置文件中的  角色的集合
//        String[] rolesArray = (String[]) mappedValue;

        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getRequestURI();
        QueryWrapper qw = new QueryWrapper();
        qw.eq("url",url);
        //从数据库获取权限的角色集合
        Power power = powerService.getOne(qw);
        String[] rolesArray;
        if(null==power){
            rolesArray = null;
        }else{
            rolesArray = new String[]{power.getpName()};
            System.out.println(rolesArray);
        }
        if (rolesArray == null || rolesArray.length == 0) { //没有角色限制，有权限访问  
            return true;
        }
        for (int i = 0; i < rolesArray.length; i++) {
            if (subject.hasRole(rolesArray[i])) { //若当前用户是rolesArray中的任何一个，则有权限访问  
                return true;
            }
        }
        HttpSession session = request.getSession();
        session.setAttribute("quanxian",false);
        return false;
    }

}